﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace General.Core.Common.SEO
{
    /// <summary>
    /// 生成站点地图sitemap
    /// </summary>
    public class GenerateSiteMap
    {
        public List<PageInfo> UrlList
        {
            get;
            set;
        }
        /// <summary>
        /// 生成SiteMap字符串
        /// </summary>
        /// <returns></returns>
        public string GenerateSiteMapString(List<PageInfo> list)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");

            foreach (PageInfo pi in list)
            {
                sb.AppendLine("<url>");
                sb.AppendLine(string.Format("<loc>{0}</loc>", pi.loc));
                if (pi.lastmod != null)
                {
                    sb.AppendLine(string.Format("<lastmod>{0}</lastmod>", Convert.ToDateTime(pi.lastmod).ToString("yyyy-MM-dd")));
                }
                if (!string.IsNullOrWhiteSpace(pi.changefreq))
                {
                    sb.AppendLine(string.Format("<changefreq>{0}</changefreq>", pi.changefreq));
                }
                if (!string.IsNullOrWhiteSpace(pi.priority))
                {
                    sb.AppendLine(string.Format("<priority>{0}</priority>", pi.priority));
                }

                sb.AppendLine("</url>");
            }

            sb.AppendLine("</urlset>");
            return sb.ToString();
        }

        /// <summary>
        /// 保存Site文件
        /// </summary>
        /// <param name="FilePath">路径</param>
        public async Task SaveSiteMap(string path, int subCount = 30000)
        {
            int allCount = UrlList.Count;
            int fileIndex = (allCount / subCount) + 1; //需要创建的文件数
            for (int i = 0; i < fileIndex; i++)
            {
                var temp = UrlList.Skip(i * subCount).Take(subCount).ToList();
                //保存在指定目录下
                await System.IO.File.WriteAllTextAsync(path + "/SiteMap/sitemap" + (i + 1).ToString() + ".xml", GenerateSiteMapString(temp));

            }

        }
    }

    public class PageInfo
    {
        /// <summary>
        /// 网址
        /// </summary>
        public string loc { get; set; }

        /// <summary>
        /// 最后更新时间
        /// </summary>
        public DateTime? lastmod { get; set; }

        /// <summary>
        /// 更新频繁程度
        /// </summary>
        public string? changefreq { get; set; }

        /// <summary>
        /// 优先级，0-1
        /// </summary>
        public string? priority { get; set; }
    }
}
